package com.durian.base.rxhttp.await

/**
 * 说明：失败重试
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/04/25 18:07
 * <p/>
 * 版本：version 1.0
 */
internal class AwaitRetry<T>(
        private val iAwait: IAwait<T>,
        private var times: Int = 0,
        private val period: Long = 0L,
        private val test: ((Throwable) -> Boolean)? = null
) : IAwait<T> {
    override suspend fun await(): T {
        return try {
            iAwait.await()
        } catch (e: Throwable) {
            val remaining = times
            if (remaining != Int.MAX_VALUE) {
                times = remaining - 1
            }
            val pass = test?.invoke(e) ?: true
            if (remaining > 0 && pass) {
                kotlinx.coroutines.delay(period)
                await()
            } else throw e
        }
    }
}